package com.lizj.sc;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<String> filterList;
    private String TAG = getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        filterList = new ArrayList<>();
        filterList.add("com.kaer.contact");
        filterList.add("com.kaer.read.demo");
//        filterList.add("org.kaer.election");
        filterList.add("com.kaeridcard.factest");
//        filterList.add("com.kaer.attendance");
//        filterList.add("com.lizj.sc");

        List<ApplicationInfo> list = getInstalledApplications();
        String permission = getAuthorityFromPermission(this, "com.android.launcher3.permission.READ_SETTINGS");
        if (permission != null) {
            String url = "content://" + permission + "/favorites?notify=true";
            Log.i("MainActivity", "url = " + url);
            for (int i = 0; i < list.size(); i++) {
                ApplicationInfo info = list.get(i);
                if (!hasShortcut(this, url, list.get(i).loadLabel(getPackageManager()).toString())) {
                    createShortCut(info);
                }
            }
        }
    }

    public List<ApplicationInfo> getInstalledApplications() {
        List<ApplicationInfo> retList = new ArrayList<>();
        try {
            PackageManager pm = getPackageManager();
            List<ApplicationInfo> list = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
            for (int i = 0; i < list.size(); i++) {
                ApplicationInfo info = list.get(i);
                //      Log.i("MainActivity ", info.toString());
                if (filterList.contains(info.packageName)) {
                    retList.add(info);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return retList;
    }

    public void createShortCut(ApplicationInfo info) {
        PackageManager pm = getPackageManager();
        Intent launchIntent = pm.getLaunchIntentForPackage(info.packageName);
        String name = info.name;
        String loadble = info.loadLabel(pm).toString();
        String lable = pm.getApplicationLabel(info).toString();
//        Log.i("MainActivity", "info.name :" + name + " , info.loadLable :" + loadble + " , pm.getLable :" + lable);
//        ShortCutDrawble icon = (ShortCutDrawble) info.loadIcon(pm);
        //创建快捷方式的Intent
        Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        //不允许重复创建
        shortcutintent.putExtra("duplicate", false);
        //需要现实的名称
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, loadble);
        //快捷图片
        //Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.icon);
//         shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON, ((BitmapDrawable) info.loadIcon(pm)).getBitmap());
        //点击快捷图片，运行的程序主入口
        shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
        //发送广播。OK
        sendBroadcast(shortcutintent);
    }

    public boolean hasShortcut(Activity activity, String contentUrl, String shortcutName) {
        ContentResolver resolver = activity.getContentResolver();
        Cursor cursor = resolver.query(Uri.parse(contentUrl), new String[]{"title", "iconResource"}, "title=?", new String[]{shortcutName.trim()}, null);
        if (cursor != null && cursor.moveToFirst()) {
            cursor.close();
            return true;
        }
        return false;
    }

    private String getAuthorityFromPermission(Context context, String permission) {
        if (permission == null)
            return null;
        List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
        if (packs != null) {
            for (PackageInfo pack : packs) {
                ProviderInfo[] providers = pack.providers;
                if (providers != null) {
                    for (ProviderInfo provider : providers) {
                        if (permission.equals(provider.readPermission))
                            return provider.authority;
                        if (permission.equals(provider.writePermission))
                            return provider.authority;
                    }
                }
            }
        }
        return null;
    }
}
